package com.hsj.springai.utils;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.ArrayList;

@Slf4j
@Aspect
@Component
public class RedisLimitAOP {
    Object result = null;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private DefaultRedisScript<Long> redisLuaScript;

    @PostConstruct
    public void init() {
       redisLuaScript = new DefaultRedisScript<>();
       redisLuaScript.setResultType(Long.class);
       redisLuaScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("rate")));
    }

    @Around("@annotation(com.hsj.springai.utils.RedisLimitAnnotation)")
    public Object around(ProceedingJoinPoint joinPoint) {
        System.out.println("------环绕通知11111");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        RedisLimitAnnotation redisLimitAnnotation = method.getAnnotation(RedisLimitAnnotation.class);
        if (redisLimitAnnotation != null) {
            String key = redisLimitAnnotation.key();
            String className = method.getDeclaringClass().getName();
            String methodName = method.getName();

            String limitKey = key + "\t" + className + "\t" + methodName;
            log.info(limitKey);

            if (null == key) {
                throw new GlobException("001", "limitKey can not be null");
            }
            long limit = redisLimitAnnotation.permitsPerSecond();
            long expire = redisLimitAnnotation.expire();
            //因为lua脚本得传入数组进去
            ArrayList<String> keys = new ArrayList<>();
            keys.add(key);

            Long count = stringRedisTemplate.execute(redisLuaScript, keys, String.valueOf(limit), String.valueOf(expire));
            System.out.println("Access try count is " + count + "\t key= " + key);

            if (count != null && count == 0) {
                System.out.println("启动限流功能 key= " + key);
                return redisLimitAnnotation.msg();
            }

        }

        try {
            result = joinPoint.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }

        System.out.println("-------环绕通知22222222");
        return result;
    }

}
